from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User,PermissionType,Permission,UserGroup
from django.contrib.auth.hashers import check_password,make_password
import jwt,redis,random
from day1 import settings
from django.utils import timezone
import time
from .serializers import UserSer,TypeSer,GroupSer,PermSer

# Create your views here.
def gen_jwt_token(user):
    obj = {
        'id':user.id,
        'username':user.username,
        'phone':user.phone
    }
    token = jwt.encode(obj,key=settings.SECRET_KEY,algorithm='HS256')
    return token

def check_code(code,phone):
    r = redis.Redis(host='localhost', port=6379, db=6)
    key = "sms_%s" % phone
    r_code = r.get(key)
    if not r_code:
        return Response({'msg':'验证码过期','code':204})
    if r_code.decode().lower() != code.lower():
        return Response({'msg':'密码错误','code':204})
    else:
        return Response({'msg':'验证成功','code':200})

class Login(APIView):
    def post(self,request):
        username = request.data.get('username')
        phone = request.data.get('phone')
        pwd = request.data.get('password')
        code = request.data.get('code')
        if not all([username,pwd,phone]):
            return Response({'msg':'用户信息未完善','code':204})
        # 验证码校验方法
        # check_code(code,phone)
        try:
            user = User.objects.get(username=username)
            if not check_password(pwd,user.password):
                return Response({'msg':'密码错误','code':204})
            user.last_login = timezone.now()
            user.save()
            return Response({
                'msg':'登录成功',
                'code':200,
                'user':{
                    'username': user.username,
                    'img':'http://127.0.0.1:8000/static/images/1.jpg',
                },
                'token':gen_jwt_token(user),
            })
        except Exception as e:
            print(e)
            user_data = User.objects.create(username=username, password=make_password(pwd), phone=phone)
            return Response({
                'msg': '注册并登录成功',
                'code': 200,
                'user':{
                    'username': user_data.username,
                    'img':'http://127.0.0.1:8000/static/images/1.jpg',
                },
                'token': gen_jwt_token(user_data)
            })


from celery_tasks.sms_code.tasks import send_sms_code
import json
# 短信验证码
class GetCode(APIView):
    def get(self,request):
        phone = request.query_params.get('phone')
        data = random.randint(000000, 999999)
        if phone:
            resp = send_sms_code.delay(phone,data)
            if resp:
                r = redis.Redis(host='localhost', port=6379, db=6)
                key = "sms_%s" % phone
                r.set(key, data, ex=600)
                r.close()
                return Response({'msg': '发送成功', 'code': 200})
            else:
                return Response({'msg': '发送失败', 'code': 204})
        else:
            return Response({'msg': '手机号不存在', 'code': 204})
        # key = "celery-task-meta-"+str(resp)
        # r = redis.Redis(host='localhost',port=6379,db=14)
        # r_sms = r.get(key)
        # print(r_sms)
        # 把json转成字典
        #     resp_data = json.loads(resp)
        #     if resp_data['statusCode'] == "000000":
        #         # 短信验证码写入数据库，便于后面校验
        #         r = redis.Redis(host='localhost',port=6379,db=6)
        #         key = "sms_%s" % phone
        #         r.set(key,data,ex=600)
        #         r.close()
        #         return Response({'msg':'发送成功','code':200})
        #     else:
        #         return Response({'msg':'发送失败','code':204})
        # else:
        #     return Response({'msg':'手机号不存在','code':204})

# 总用户视图
class UserCount(APIView):
    def get(self,request):
        num = User.objects.all().count()
        return Response({'msg':'获取成功','code':200,'total_count':num})

# 日增试图
class Increment(APIView):
    def get(self,request):
        day_time = time.strftime("%y-%m-%d")
        try:
            num = User.objects.filter(created_time__contains=day_time).count()
            return Response({'msg':'ok','code':200,'total_count':num})
        except Exception as e:
            return Response({'msg':'获取失败','code':204})

# 日活视图
class Live(APIView):
    def get(self,request):
        day_time = time.strftime("%y-%m-%d")
        # day_time = timezone.now()
        num = User.objects.filter(last_login__contains=day_time).count()
        return Response({'msg':'ok','code':200,'total_count':num})

# 获取当月每天增加数量
import datetime
from django.db.models import Count
from django.db import connection
from django.http import JsonResponse
class MonthIncrement(APIView):
    def get(self,request):
       day = time.strftime('%y-%m',time.localtime(time.time()))
       select = {'day':connection.ops.date_trunc_sql('day','created_time')}
       data = User.objects.filter(created_time__contains=day).extra(select=select).values('day').annotate(number=Count('id'))

       data_list = []
       for i in data:
           data_list.append({
               'count':i['number'],
               'day':i['day']
           })
       return JsonResponse(data_list,safe=False)



class GoodsDayViews(APIView):
    def get(self,request):
       day = time.strftime('%y-%m',time.localtime(time.time()))
       select = {'day':connection.ops.date_trunc_sql('day','last_login')}
       data = User.objects.filter(last_login__contains=day).extra(select=select).values('day').annotate(number=Count('id'))
       data_list = []
       for i in data:
           data_list.append({
               'count':i['number'],
               'day':i['day']
           })
       return JsonResponse(data_list,safe=False)



from .utils import MyPagination
from rest_framework.generics import ListCreateAPIView
class UserAll(ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSer
    pagination_class = MyPagination

# class UserAll(APIView):
#     def get(self,request):
#         user_data = User.objects.all()
#
#         ser = UserSer(user_data,many=True)
#         return Response({'msg':'ok','code':200,'data':ser.data})


class AddUser(APIView):
    def post(self,request):
        name = request.data.get('username')
        pwd = request.data.get('password')
        mobile = request.data.get('mobile')
        email = request.data.get('email')
        if not all([name,pwd,mobile,email]):
            return Response({'msg':'信息不完善','code':204})
        try:
            User.objects.get(username=name)
            return Response({'msg':'用户已存在','code':204})
        except Exception as e:
            User.objects.create(username=name,password=make_password(pwd),phone=mobile,email=email)
            return Response({'msg':'添加成功','code':200})

class DelUser(APIView):
    def delete(self,request,edit_id):
        try:
            User.objects.get(id=edit_id).delete()
            return Response({'msg': '删除成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'删除失败','code':204})
    def put(self,request,edit_id):
        name = request.data.get('username')
        pwd = request.data.get('password')
        mobile = request.data.get('mobile')
        email = request.data.get('email')
        try:
            user=User.objects.get(id=edit_id)
            if check_password(pwd,user.password):
                user.username = name
                user.email = email
                user.phone = mobile
                user.save()
                print(user.phone)
            else:
                user.username = name
                user.email = email
                user.phone = mobile
                user.password = make_password(pwd)
                user.save()
                print(user.phone)
            return Response({'msg': '修改成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'修改失败','code':204})


class PutUser(APIView):
    def get(self,request,id):
        try:
           use_data = User.objects.get(id=id)
           ser = UserSer(use_data)
           return Response(ser.data)
        except Exception as e:
            return Response({'msg':'没有该数据','code':204})

from django.db.models import Q
class GetOne(APIView):
    def get(self,request):
        data = request.query_params.get('num')
        user = User.objects.filter(Q(username=data)|Q(phone=data)|Q(email=data)).all()
        if user.count() == 0:
            return Response({'msg': '没有找到相对应的信息', 'code': 204})
        else:
            ser = UserSer(user, many=True)
            return Response({'msg': 'ok', 'code': 200,'data':ser.data})


class GetType(APIView):
    def get(self,request):
        data = PermissionType.objects.all()
        ser = TypeSer(data,many=True)
        return Response(ser.data)


class AddPerm(APIView):
    def post(self,request):
        name=request.data.get('name')
        code_name = request.data.get('codename')
        type_id = request.data.get('content_type')
        try:
            Permission.objects.create(
                name=name,
                code_name=code_name,
                type_name_id=type_id
            )
            return Response({'msg':'添加成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg': '添加失败', 'code': 500})


class GetProm(APIView):
    def get(self,request):
        page = int(request.query_params.get('page'))
        size = int(request.query_params.get('size'))
        data = Permission.objects.all()[((page-1)*size):(page*size)]
        ser = PermSer(data,many=True)
        return Response({'data':ser.data,'count':Permission.objects.all().count()})

class OneProm(APIView):
    def get(self,request,id):
        try:
            data = Permission.objects.get(id=id)
            ser = PermSer(data)
            return Response(ser.data)
        except Exception as e:
            print(e)
            return Response({'msg':'没有相对应的数据','code':204})
    def put(self,request,id):
        name = request.data.get('name')
        code_name = request.data.get('codename')
        type_id = request.data.get('content_type')
        try:
            data = Permission.objects.get(id=id)
            data.name = name
            data.code_name = code_name
            data.type_name_id = type_id
            return Response({'msg':'修改成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'没有相对应的数据','code':204})

    def delete(self, request,id):
        try:
            Permission.objects.get(id=id).delete()
            return Response({'msg':'删除成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'没有相对应的数据','code':204})


class GetGroup(APIView):
    def get(self,request):
        page = int(request.query_params.get('page'))
        size = int(request.query_params.get('size'))
        data = UserGroup.objects.all()[((page - 1) * size):(page * size)]
        ser = GroupSer(data, many=True)
        return Response({'data': ser.data, 'count': UserGroup.objects.all().count()})


class AllUser(APIView):
    def get(self,request):
        ser = UserSer(User.objects.all(),many=True)
        return Response(ser.data)

class AllPerm(APIView):
    def get(self,request):
        ser = PermSer(Permission.objects.all(),many=True)
        return Response(ser.data)

class AllGroup(APIView):
    def get(self,request):
        ser = GroupSer(UserGroup.objects.all(),many=True)
        return Response(ser.data)

class AddGroup(APIView):
    def post(self,request):
        ser = GroupSer(data=request.data)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({'msg':'添加成功','code':200})
        else:
            return Response({'msg':'添加失败','code': 204})


class OneGroup(APIView):
    def get(self,request,id):
        try:
            ser = GroupSer(UserGroup.objects.get(id=id))
            return Response(ser.data)
        except Exception as e:
            print(e)
            return Response({'msg':'获取失败','code':204})

    def put(self,request,id):
        try:
            group = UserGroup.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg':'获取失败','code':204})
        ser = GroupSer(instance=group, data=request.data,partial=True)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({'msg':'修改成功','code':200})
        else:
            return Response({'msg':'修改失败','code':204})

    def delete(self,request,id):
        try:
            UserGroup.objects.get(id=id).delete()
            return Response({'msg': '删除成功','code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'删除失败','code':204})


class AdminView(APIView):
    def post(self,request):
        user = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        groups = request.data.get('groups')
        user_permissions = request.data.get('user_permissions')
        try:
            User.objects.get(username=user)
            return Response({'msg':'用户已存在','code':204})
        except Exception as e:
            user_data = User.objects.create(
                username=user,
                password=make_password(password),
                phone=phone,
                email=email,
            )
        user_data.usergroup_set.set(groups)
        for i in groups:
            group = UserGroup.objects.get(id=i)
            group.permission.set(user_permissions)
            group.save()
        return Response({'msg':'添加管理员成功','code':200})

    def  get(self,request):
        page = int(request.query_params.get('page'))
        size = int(request.query_params.get('size'))
        data = User.objects.filter(is_staff=True)[((page-1)*size):(page*size)]
        ser = UserSer(data,many=True)
        return Response({'data':ser.data,'count':User.objects.filter(is_staff=True).count()})


class AdminInfo(APIView):
    def get(self,request,id):
        try:
            user = User.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg':'没有获取到该用户','code':204})
        groups = GroupSer(user.usergroup_set.all(),many=True)
        ser = UserSer(user)
        data = ser.data
        data['groups'] = groups.data
        # per_list = []
        # for i in groups:
        #     ser = PermSer(i.permission.all(),many=True)
        #     print('>>>>>>>>>>.',ser.data)
        return Response(data)
